import { useState } from 'react';
import { Button } from '../components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../components/ui/card';
import { Badge } from '../components/ui/badge';
import { Plus, Bookmark, Star, Trash2, Search, MessageSquare } from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '../components/ui/dialog';
import { Input } from '../components/ui/input';
import { Label } from '../components/ui/label';
import { Textarea } from '../components/ui/textarea';
import { toast } from '../hooks/use-toast';

interface BookmarkItem {
  id: string;
  title: string;
  prompt: string;
  description?: string;
  category: string;
  isFavorite: boolean;
  createdAt: Date;
  usageCount: number;
}

export default function BookmarksPage() {
  const [bookmarks, setBookmarks] = useState<BookmarkItem[]>([
    {
      id: '1',
      title: 'Code Review',
      prompt: 'Please review this code for best practices, potential bugs, and improvements.',
      description: 'General code review template',
      category: 'Development',
      isFavorite: true,
      createdAt: new Date('2024-01-15'),
      usageCount: 15,
    },
    {
      id: '2',
      title: 'Email Writing',
      prompt: 'Help me write a professional email for the following situation:',
      description: 'Professional email composition',
      category: 'Communication',
      isFavorite: false,
      createdAt: new Date('2024-01-20'),
      usageCount: 8,
    },
  ]);
  
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [newBookmark, setNewBookmark] = useState({
    title: '',
    prompt: '',
    description: '',
    category: '',
  });

  const categories = ['all', ...Array.from(new Set(bookmarks.map(b => b.category)))];

  const handleCreateBookmark = async () => {
    try {
      const bookmark: BookmarkItem = {
        id: Date.now().toString(),
        title: newBookmark.title,
        prompt: newBookmark.prompt,
        description: newBookmark.description,
        category: newBookmark.category,
        isFavorite: false,
        createdAt: new Date(),
        usageCount: 0,
      };
      
      setBookmarks(prev => [...prev, bookmark]);
      setIsCreateDialogOpen(false);
      setNewBookmark({
        title: '',
        prompt: '',
        description: '',
        category: '',
      });
      
      toast({
        title: "Bookmark Created",
        description: `"${bookmark.title}" has been added to your bookmarks.`,
      });
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to create bookmark. Please try again.",
        variant: "destructive",
      });
    }
  };

  const handleDeleteBookmark = (bookmarkId: string) => {
    setBookmarks(prev => prev.filter(bookmark => bookmark.id !== bookmarkId));
    toast({
      title: "Bookmark Deleted",
      description: "Bookmark has been removed.",
    });
  };

  const handleToggleFavorite = (bookmarkId: string) => {
    setBookmarks(prev => prev.map(bookmark => 
      bookmark.id === bookmarkId 
        ? { ...bookmark, isFavorite: !bookmark.isFavorite }
        : bookmark
    ));
  };

  const handleUseBookmark = (bookmark: BookmarkItem) => {
    // Increment usage count
    setBookmarks(prev => prev.map(b => 
      b.id === bookmark.id 
        ? { ...b, usageCount: b.usageCount + 1 }
        : b
    ));
    
    // Navigate to chat with the prompt
    // This would typically navigate to the chat page with the prompt pre-filled
    toast({
      title: "Bookmark Used",
      description: `Using "${bookmark.title}" prompt in chat.`,
    });
  };

  const filteredBookmarks = bookmarks.filter(bookmark => {
    const matchesSearch = bookmark.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         bookmark.prompt.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         bookmark.description?.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCategory = selectedCategory === 'all' || bookmark.category === selectedCategory;
    return matchesSearch && matchesCategory;
  });

  const favoriteBookmarks = filteredBookmarks.filter(b => b.isFavorite);
  const regularBookmarks = filteredBookmarks.filter(b => !b.isFavorite);

  return (
    <div className="flex flex-col h-full p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold">Bookmarks</h1>
          <p className="text-slate-600 dark:text-slate-400">
            Save and organize your favorite prompts and conversations
          </p>
        </div>
        
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              Create Bookmark
            </Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[500px]">
            <DialogHeader>
              <DialogTitle>Create New Bookmark</DialogTitle>
              <DialogDescription>
                Save a prompt or conversation for quick access later.
              </DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid gap-2">
                <Label htmlFor="title">Title</Label>
                <Input
                  id="title"
                  value={newBookmark.title}
                  onChange={(e) => setNewBookmark({ ...newBookmark, title: e.target.value })}
                  placeholder="Enter bookmark title"
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="prompt">Prompt</Label>
                <Textarea
                  id="prompt"
                  value={newBookmark.prompt}
                  onChange={(e) => setNewBookmark({ ...newBookmark, prompt: e.target.value })}
                  placeholder="Enter the prompt text"
                  rows={4}
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="description">Description (Optional)</Label>
                <Input
                  id="description"
                  value={newBookmark.description}
                  onChange={(e) => setNewBookmark({ ...newBookmark, description: e.target.value })}
                  placeholder="Brief description of this bookmark"
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="category">Category</Label>
                <Input
                  id="category"
                  value={newBookmark.category}
                  onChange={(e) => setNewBookmark({ ...newBookmark, category: e.target.value })}
                  placeholder="e.g., Development, Writing, Research"
                />
              </div>
            </div>
            <div className="flex justify-end gap-2">
              <Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
                Cancel
              </Button>
              <Button onClick={handleCreateBookmark} disabled={!newBookmark.title || !newBookmark.prompt}>
                Create Bookmark
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* Search and Filter */}
      <div className="flex gap-4 mb-6">
        <div className="flex-1 relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-slate-400" />
          <Input
            placeholder="Search bookmarks..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10"
          />
        </div>
        <select
          value={selectedCategory}
          onChange={(e) => setSelectedCategory(e.target.value)}
          className="px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-md bg-white dark:bg-slate-800"
        >
          {categories.map(category => (
            <option key={category} value={category}>
              {category === 'all' ? 'All Categories' : category}
            </option>
          ))}
        </select>
      </div>

      {/* Bookmarks */}
      <div className="flex-1 overflow-auto space-y-6">
        {/* Favorites */}
        {favoriteBookmarks.length > 0 && (
          <div>
            <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
              <Star className="h-5 w-5 text-yellow-500" />
              Favorites
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {favoriteBookmarks.map((bookmark) => (
                <Card key={bookmark.id} className="hover:shadow-md transition-shadow border-yellow-200 dark:border-yellow-800">
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <CardTitle className="text-lg flex items-center gap-2">
                        <Bookmark className="h-4 w-4" />
                        {bookmark.title}
                      </CardTitle>
                      <div className="flex items-center gap-1">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleToggleFavorite(bookmark.id)}
                        >
                          <Star className="h-4 w-4 fill-yellow-500 text-yellow-500" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDeleteBookmark(bookmark.id)}
                          className="text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                    <CardDescription>{bookmark.description}</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-3">
                      <p className="text-sm text-slate-600 dark:text-slate-400 line-clamp-3">
                        {bookmark.prompt}
                      </p>
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <Badge variant="outline">{bookmark.category}</Badge>
                          <span className="text-xs text-slate-500">
                            Used {bookmark.usageCount} times
                          </span>
                        </div>
                        <Button
                          size="sm"
                          onClick={() => handleUseBookmark(bookmark)}
                        >
                          <MessageSquare className="h-4 w-4 mr-1" />
                          Use
                        </Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          </div>
        )}

        {/* Regular Bookmarks */}
        {regularBookmarks.length > 0 && (
          <div>
            <h2 className="text-lg font-semibold mb-4">All Bookmarks</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {regularBookmarks.map((bookmark) => (
                <Card key={bookmark.id} className="hover:shadow-md transition-shadow">
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <CardTitle className="text-lg flex items-center gap-2">
                        <Bookmark className="h-4 w-4" />
                        {bookmark.title}
                      </CardTitle>
                      <div className="flex items-center gap-1">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleToggleFavorite(bookmark.id)}
                        >
                          <Star className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleDeleteBookmark(bookmark.id)}
                          className="text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                    <CardDescription>{bookmark.description}</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-3">
                      <p className="text-sm text-slate-600 dark:text-slate-400 line-clamp-3">
                        {bookmark.prompt}
                      </p>
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <Badge variant="outline">{bookmark.category}</Badge>
                          <span className="text-xs text-slate-500">
                            Used {bookmark.usageCount} times
                          </span>
                        </div>
                        <Button
                          size="sm"
                          onClick={() => handleUseBookmark(bookmark)}
                        >
                          <MessageSquare className="h-4 w-4 mr-1" />
                          Use
                        </Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          </div>
        )}

        {/* Empty State */}
        {filteredBookmarks.length === 0 && (
          <div className="flex flex-col items-center justify-center h-64 text-center">
            <Bookmark className="h-12 w-12 text-slate-400 mb-4" />
            <h3 className="text-lg font-semibold mb-2">
              {bookmarks.length === 0 ? "No Bookmarks Yet" : "No Results Found"}
            </h3>
            <p className="text-slate-600 dark:text-slate-400 mb-4">
              {bookmarks.length === 0 
                ? "Save your favorite prompts and conversations for quick access."
                : "Try adjusting your search query or category filter."
              }
            </p>
            {bookmarks.length === 0 && (
              <Button onClick={() => setIsCreateDialogOpen(true)}>
                <Plus className="h-4 w-4 mr-2" />
                Create Your First Bookmark
              </Button>
            )}
          </div>
        )}
      </div>
    </div>
  );
}